use base64::engine::general_purpose::STANDARD;
use serde_json::Value;
use std::fs;
use std::path::Path;
use super::models::ImageData;
use base64::Engine;
pub fn read_dir_all_image(image_dir_path: &str) -> Vec<ImageData> {
    let mut images = Vec::new();
    if let Ok(entries) = fs::read_dir(image_dir_path) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                let filename = path.file_stem()
                    .and_then(|n| n.to_str())
                    .unwrap_or_default()
                    .to_string();

                let ext = path.extension()
                    .and_then(|e| e.to_str())
                    .unwrap_or("unknown")
                    .to_lowercase();

                if let Ok(file_data) = fs::read(&path) {
                    images.push(ImageData {
                        name: filename,
                        imgtype: ext,
                        base64_header:"data:image/jpeg;base64,".to_string(),
                        url: STANDARD.encode(&file_data),
                        mes_type: "image".to_string(),
                        user_id: None,
                    });
                }
            }
        }
    }
    images
}

pub fn delete_image(_path: &str, image_info: &Value) {
    let path_str = Path::new(_path);
    let image_name = image_info["name"].as_str().unwrap();
    let image_path = path_str.join(format!("{}.jpg", image_name));
    if let Err(e) = fs::remove_file(&image_path) {
        eprintln!("删除图片失败: {}", e);
    }
}

pub fn add_image(_path: &str, image_info: &Value) {
    let image_name = image_info["name"].as_str().unwrap();
    let image_path = format!("{}/{}.jpg", _path, image_name);
    let image_url = image_info["url"].as_str().unwrap();

    let bytes = STANDARD.decode(image_url)
        .unwrap_or_else(|e| panic!("解码失败: {}", e));

    fs::write(&image_path, &bytes)
        .unwrap_or_else(|e| panic!("文件写入失败: {}", e));
}